package com.example.whever.lacation;

import androidx.annotation.NonNull;

import com.example.whever.AppConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherManager {
    private static final Gson GSON = new GsonBuilder().create();
    private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient();

    public static void queryWeather(String location, WeatherApiCallback callback) {
        HttpUrl httpUrl = new HttpUrl.Builder()
                .scheme("https")
                .host("devapi.qweather.com")
                .addEncodedPathSegments("v7/weather/3d")
                .addEncodedQueryParameter("language", "zh")
                .addEncodedQueryParameter("key", AppConfig.Q_WEATHER_API_KEY)
                .addEncodedQueryParameter("location", location)
                .build();
        Request request = new Request.Builder()
                .url(httpUrl)
                .build();
        OK_HTTP_CLIENT.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                callback.onSuccess(GSON.fromJson(json, WeatherApiResponse.class));
            }
        });
    }
}
